
package hasthi.metamodel;

import hasthi.common.HasthiException;
import hasthi.metamodel.resource.AbstractResourceModel;
import hasthi.metamodel.resource.ManagedResource;
import hasthi.metamodel.resource.ResourceModelContext;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

public class ExternalResourceModel extends AbstractResourceModel {
    private Map<QName,String> holderMap = new HashMap<QName, String>();
    private Map<QName,ManagedResource> resourceCache = new HashMap<QName, ManagedResource>();
    
    
    public ExternalResourceModel(ResourceModelContext context) throws HasthiException {
        super(context);
    }

    public ManagedResource getResource(QName name) throws HasthiException {
        ManagedResource resource = resourceCache.get(name);
        if(resource != null){
            return resource;
        }else{
            String holderURL = holderMap.get(name);
            if(holderURL == null){
                holderURL = ResourceUtils.fetchHolderURL(context,name);
                if(holderURL != null){
                    holderMap.put(name,holderURL);
                }
            }
            if(holderURL != null){
                return fetchRemoteResource(holderURL, name,false);    
            }else{
                return null;
            }
        }
    }

    /**
     * There is no resources held locally, so return null
     */
    public Collection<QName> getResources() {
        return null;
    }
    
    /**
     * Get all resources, and add it to a local cache 
     * @return
     * @throws HasthiException 
     */
    public ManagedResource[] getAllResources() throws HasthiException{
        resourceCache.clear();
        ManagedResource[] resourcesSummery = super.getAllResources();
        for(ManagedResource resource:resourcesSummery){
            resourceCache.put(resource.getQName(), resource);
        }
        return resourcesSummery;
    }
    
    public void reload() throws HasthiException, InterruptedException{
        resourceCache.clear();
        super.reload();
    }
    
    
    
    //TODO start a thread to update the resource model time to time
    
}

